package com.zbf.web;

import com.alibaba.fastjson.JSON;
import com.zbf.common.ResponseResult;
import com.zbf.common.ResultStatus;
import com.zbf.dao.UserMapper;
import com.zbf.utils.MD5;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author: LCG
 * 作者: LCG
 * 日期: 2021/6/25  16:15
 * 描述:
 */
@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @RequestMapping("/toLogin")
    public ResponseResult toLogin(@RequestBody Map<String,String> map){

        ResponseResult responseResult=null;
        //1根据用户名查询用户信息
        Map<String, Object> info = userMapper.getUserInfoByUserName(map.get("userName"));
        //2判断有没有渠道用户信息 没有取到用户信息则直接返回用户名或者密码错误
        //如果取到了用户信息校验密码
        if(info==null){
            responseResult = ResponseResult.getResponseResult()
                    .setMsg(ResultStatus.AUTH_LOGIN_FAIL.getMsg())
                    .setCode(ResultStatus.AUTH_LOGIN_FAIL.getCode());
            return responseResult;
        }else{
            //3、校验密码  校验密码通过  存redis 返回token
            //校验不通过 返回 用户名或者密码错误
            String encryptPassword = MD5.encryptPassword(map.get("password"), map.get("userName"));
            if(encryptPassword.equals(info.get("password").toString())){

                String replace = UUID.randomUUID().toString().replace("-", "");

                redisTemplate.opsForValue().set(replace, JSON.toJSONString(info));
                redisTemplate.expire(replace,300,TimeUnit.SECONDS);

                Map<String,String> userInfo=new HashMap<String, String>();
                userInfo.put("token",replace);
                userInfo.put("userId",info.get("id").toString());
                userInfo.put("userName",info.get("userName").toString());


                responseResult = ResponseResult.getResponseResult()
                        .setMsg(ResultStatus.AUTH_LOGIN_SUCCESS.getMsg())
                        .setCode(ResultStatus.AUTH_LOGIN_SUCCESS.getCode())
                        .setResult(userInfo);


                return responseResult;
            }else{
                //密码校验不通过
                responseResult = ResponseResult.getResponseResult()
                        .setMsg(ResultStatus.AUTH_LOGIN_FAIL.getMsg())
                        .setCode(ResultStatus.AUTH_LOGIN_FAIL.getCode());
                return responseResult;
            }

        }

    }

}
